#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time      :2021/11/1 13:37
# @Author    :cjw
import json
from typing import Optional

import allure
import requests
from requests.models import Response

from use_custom_api.util.log import logging


class BaseApi:

	def request(self, data: dict) -> Response:
		"""
		发送请求
		:param data: 请求数据
		:return:
		"""
		# 为了多协议支持，或者将来协议变更，或者将来方便切换不同的http库
		if 'url' in data:
			# 返回的是生成器，所以获取值需要用next函数
			return next(self._http_request(data))

	def _http_request(self, data: dict) -> Response:
		"""
		发送http/https请求, 返回响应后，再关闭http连接
		:param data: 请求数据
		:return:
		"""
		rsp: Optional[Response] = None
		try:
			with allure.step(msg := f'发送{data.get("method")}请求：{data.get("url")}'):
				logging.info(msg)
				logging.info(f'\n============================== 请求参数 =============================='
				             f'\n{json.dumps(data, indent=2,ensure_ascii=False)}')
			rsp = requests.request(**data)
			# 格式化缩进打印返回响应数据
			with allure.step(f'响应结果: {rsp.json()}'):
				logging.info(f'\n============================== 响应结果 =============================='
				             f'\n{json.dumps(rsp.json(), indent=2, ensure_ascii=False)}')
			yield rsp
		except Exception as e:
			with allure.step(msg := f'请求异常：{e}'):
				logging.error(msg)
			raise e
		finally:
			with allure.step(msg := f'关闭请求连接：{rsp.url}'):
				logging.info(msg)
			rsp.close()
